package com.jvnsrp.mirror;

import java.io.*;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Jevon
 * @version V1.0
 * @date 2021/6/20 20:58
 **/
public class MD5Utils {
    public static String md5sums(File file) {
        int len = 0;
        byte[] buffer = new byte[8192];
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            InputStream inputStream = new FileInputStream(file);
            while ((len = inputStream.read(buffer)) != -1) {
                digest.update(buffer, 0, len);
            }
            BigInteger bigInteger = new BigInteger(1, digest.digest());
            return bigInteger.toString(16);
        } catch (Exception e) {
            return null;
        }
    }

    public static String md5sums(String str) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(str.getBytes("UTF8"));
            BigInteger bigInt = new BigInteger(1, digest.digest());
            return bigInt.toString(16);
        } catch (Exception e) {
            return null;
        }
    }

    private static Map md5map;

    public static Map getMd5map(File dir){
        md5map = new HashMap<String,String>();
        md5Directory(dir);
        return md5map;
    }

    public static int md5Directory(File dir){
        if (dir.exists()) {
            File[] files = dir.listFiles();
            if (null != files) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        md5Directory(file);
                    } else {
                        md5map.put(file.getAbsolutePath(), md5sums(file));
                    }
                }
            }
        } else {
            System.out.println("目录不存在!");
            return -1;
        }
        return 1;
    }
}
